package org.example.server;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class HttpServerCommon {
    private final String body;

    public HttpServerCommon(String body) {
        this.body = body;
    }

    public void service(Socket s) {
        try {
            processRequest(s.getInputStream());
            processResponse(s.getOutputStream());
            s.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void processRequest(InputStream is) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.isEmpty()) {
                break;
            }
        }
    }

    private void processResponse(OutputStream os) {
        PrintWriter writer = new PrintWriter(os);
        writer.println("HTTP/1.1 200 OK");
        writer.println("Content-Type:text/html;charset=utf-8");
        writer.println("Content-Length:" + body.getBytes(StandardCharsets.UTF_8).length);
        writer.println();
        writer.write(body);
        writer.flush();
    }
}
